package com.um.jdy.platform.baofu.scheduled;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.baofu.api.BaoFuAccountService;
import com.um.jdy.baofu.config.BFConfig;
import com.um.jdy.baofu.entity.account.*;
import com.um.jdy.baofu.utils.FormatUtil;
import com.um.jdy.common.baofu.entity.po.BaofuAccountDetails;
import com.um.jdy.common.baofu.enums.BaofuEnum;
import com.um.jdy.common.baofu.service.BaofuAccountDetailsService;
import com.um.jdy.common.charge.entity.po.DataLog;
import com.um.jdy.common.charge.entity.po.Order;
import com.um.jdy.common.charge.enums.OrderAction;
import com.um.jdy.common.charge.enums.OrderStopReason;
import com.um.jdy.common.charge.service.DataLogService;
import com.um.jdy.common.charge.service.OrderService;
import com.um.jdy.common.finance.entity.po.MerchantBill;
import com.um.jdy.common.finance.entity.po.PlatformBill;
import com.um.jdy.common.finance.enums.FinancialEnum;
import com.um.jdy.common.finance.service.MerchantBillService;
import com.um.jdy.common.finance.service.PlatformBillService;
import com.um.jdy.common.month.entity.po.CardOrder;
import com.um.jdy.common.month.entity.po.CardOrderCommission;
import com.um.jdy.common.month.service.CardOrderCommissionService;
import com.um.jdy.common.month.service.CardOrderService;
import com.um.jdy.platform.baofu.entity.vo.BaofuCashoutUserVO;
import com.um.jdy.platform.baofu.entity.vo.BaofuCommissionItemVO;
import com.um.jdy.platform.baofu.manager.BaofuManager;
import com.um.jdy.rpc.enums.DeviceTypeEnum;
import com.um.springboot.starter.utils.OrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 执行宝付分账 定时任务
 */
@Slf4j
@Component
public class BaofuFenzhangTask {

    @Autowired
    OrderService orderService;
    @Autowired
    BaoFuAccountService baoFuAccountService;
    @Autowired
    DataLogService dataLogService;

    @Autowired
    private BaofuManager baofuManager;
    @Autowired
    private CardOrderCommissionService commissionService;

    @Autowired
    private CardOrderService cardOrderService;

    @Autowired
    private BaofuAccountDetailsService accountDetailsService;

    @Autowired
    private MerchantBillService merchantBillService;

    @Autowired
    private PlatformBillService platformBillService;





    /**
     * 查询可分账订单进行分账
     */
    @Async
    @Scheduled(cron = "${baofu.account.splitAccountsCron}")
    @Profile({"dev"})
    public void ordersSplitAccounts() {
        log.info("执行自动分账定时任务");
        List<Order> orders = orderService.getListBySqlName("get_baofu_split_order_list",null);

        if(orders!=null&&orders.size()>0){
            log.info("执行充电订单分账");
            for(Order order:orders){
                //查询分账数据
                try{
                    ValuesActionEntity actionEntity = null;
                    List<ValuesAcctInfoEntity> acctInfo =  new ArrayList<>();
                    ValuesAcctInfoEntity acctInfoEntity =  null;
                    List<BaofuCommissionItemVO> commissionItemVOS = orderService.getViewModelList("get_baofu_commission_list",BaofuCommissionItemVO.class,new Object[]{order.getChargeOrderId()});
                    if(commissionItemVOS!=null&&commissionItemVOS.size()>0){
                        List<BaofuAccountDetails> accountDetails = new ArrayList<>();
                        List<BaofuCommissionItemVO> vlist = commissionItemVOS.stream().filter(e->StrUtil.isBlank(e.getBaofuUserId())).collect(Collectors.toList());
                        if(vlist != null && vlist.size()>0){
                            vlist.forEach(e->{
                                log.info("用户："+e.getName()+" 未开户，所以此订单暂不支持分账，订单id:"+e.getChargeOrderId());
                            });
                        }else {
                            Integer dealAmount = 0;
                            //分账操作
                            actionEntity = new ValuesActionEntity();
                            String transSerialNo =OrderUtil.getTxOrderNo();
                            //账户流水
                            List<MerchantBill> bills = new ArrayList<>();
                            for(BaofuCommissionItemVO vo:commissionItemVOS){
                                acctInfoEntity = new ValuesAcctInfoEntity();
                                acctInfoEntity.setContractNo(vo.getContractNo());
                                acctInfoEntity.setTransAmount(new BigDecimal(vo.getCommission()).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                                acctInfoEntity.setRemark("订单："+order.getOutTradeNo()+"进行比分账");
                                dealAmount = dealAmount + vo.getCommission();
                                acctInfo.add(acctInfoEntity);
                                //写人账户明细数据
                                BaofuAccountDetails details = new BaofuAccountDetails();
                                details.setCommissionId(vo.getChargeOrderCommissionId());
                                details.setContractNo(vo.getContractNo());
                                details.setCommission(vo.getCommission());
                                details.setCommissionRate(vo.getCommissionRate());
                                details.setChargeOrderId(order.getChargeOrderId());
                                details.setTransSerialNo(transSerialNo);
                                details.setOutTradeNo(order.getOutTradeNo());
                                details.setOrderAmount(order.getOrderAmount());
                                details.setAccountType(FinancialEnum.IncomeOrExpend.Income.name());
                                details.setType(BaofuEnum.OrderType.charge.name());
                                details.setCreateTime(new Date());
                                //details.setBaofuAccountDetailsId(UUID.randomUUID().toString().replaceAll("-",""));
                                accountDetails.add(details);

                                bills.add(getMerchantBill(order.getComId(), vo.getPlatformMerchantId(), vo.getCommission(),order.getOutTradeNo()));
                            }
                            actionEntity.setAcctInfo(acctInfo);
                            actionEntity.setTransOrderNo("TSN"+ FormatUtil.CreateAeskey(20));
                            actionEntity.setTransSerialNo(transSerialNo);
                            actionEntity.setOrderNo(order.getOutTradeNo());
                            actionEntity.setDealAmount(new BigDecimal(dealAmount).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                            ContentBodyEntity<RsultBodyEntity> contentBody = baoFuAccountService.BCT3_5001_001_01(actionEntity);
                            if (contentBody.getBody().getState() == 1){
                                //修改订单状态
                                order.setIsBaofuSplit(1);
                                orderService.saveRow(order);
                                saveChargeData(order.getComId(),order.getChargeOrderId(),OrderAction.Baofu.BaofuBalanceIncrease,new Date(),
                                        actionEntity,"宝付分账");
                                //添加宝付流水
                                addBaofuAccountDetails(accountDetails);

                                //添加商户流程
                                addMerchantBill(bills);
                            }

                        }
                    }


                    //严重数据
                }catch (Exception e){
                    log.error("订单："+order.getOutTradeNo()+" 分账失败,原因："+e.getMessage());
                }
            }
        }
        List<CardOrder> monthCardOrders = cardOrderService.getListBySqlName("get_baofu_split_month_card_order_list",null);
        if(monthCardOrders!=null&&monthCardOrders.size()>0){
            log.info("执行月卡分账");
            for(CardOrder order:monthCardOrders){
                //查询分账数据
                try{
                    ValuesActionEntity actionEntity = null;
                    List<ValuesAcctInfoEntity> acctInfo =  new ArrayList<>();
                    ValuesAcctInfoEntity acctInfoEntity =  null;
                    List<BaofuCommissionItemVO> commissionItemVOS = commissionService.getViewModelList("get_baofu_commission_list_bymonthcard",BaofuCommissionItemVO.class,new Object[]{order.getMonthCardOrderId()});
                    if(commissionItemVOS!=null&&commissionItemVOS.size()>0){
                        List<BaofuAccountDetails> accountDetails = new ArrayList<>();
                        List<BaofuCommissionItemVO> vlist = commissionItemVOS.stream().filter(e->StrUtil.isBlank(e.getBaofuUserId())).collect(Collectors.toList());
                        if(vlist != null && vlist.size()>0){
                            vlist.forEach(e->{
                                log.info("用户："+e.getName()+" 未开户，所以此月卡订单暂不支持分账，订单id:"+e.getChargeOrderId());
                            });
                        }else {
                            Integer dealAmount = 0;
                            //分账操作
                            actionEntity = new ValuesActionEntity();
                            String transSerialNo = OrderUtil.getTxOrderNo();

                            //账户流水
                            List<MerchantBill> bills = new ArrayList<>();
                            for(BaofuCommissionItemVO vo:commissionItemVOS){
                                acctInfoEntity = new ValuesAcctInfoEntity();
                                acctInfoEntity.setContractNo(vo.getContractNo());
                                acctInfoEntity.setTransAmount(new BigDecimal(vo.getCommission()).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                                acctInfoEntity.setRemark("订单："+order.getOutTradeNo()+"进行比分账");
                                dealAmount = dealAmount + vo.getCommission();
                                acctInfo.add(acctInfoEntity);

                                //写人账户明细数据
                                BaofuAccountDetails details = new BaofuAccountDetails();
                                details.setCommissionId(vo.getChargeOrderCommissionId());
                                details.setContractNo(vo.getContractNo());
                                details.setCommission(vo.getCommission());
                                details.setCommissionRate(vo.getCommissionRate());
                                details.setChargeOrderId(order.getMonthCardOrderId());
                                details.setTransSerialNo(transSerialNo);
                                details.setOutTradeNo(order.getOutTradeNo());
                                details.setOrderAmount(order.getPayAmount());
                                details.setAccountType(FinancialEnum.IncomeOrExpend.Income.name());
                                details.setType(BaofuEnum.OrderType.monthCard.name());
                                details.setCreateTime(new Date());
                                //details.setBaofuAccountDetailsId(UUID.randomUUID().toString().replaceAll("-",""));
                                accountDetails.add(details);

                                bills.add(getMerchantBill(order.getComId(), vo.getPlatformMerchantId(), vo.getCommission(),order.getOutTradeNo()));
                            }
                            actionEntity.setAcctInfo(acctInfo);
                            actionEntity.setTransOrderNo("TSN"+ FormatUtil.CreateAeskey(20));
                            actionEntity.setTransSerialNo(transSerialNo);
                            actionEntity.setOrderNo(order.getOutTradeNo());
                            actionEntity.setDealAmount(new BigDecimal(dealAmount).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                            ContentBodyEntity<RsultBodyEntity> contentBody = baoFuAccountService.BCT3_5001_001_01(actionEntity);
                            if (contentBody.getBody().getState() == 1){
                                //修改订单状态
                                order.setIsBaofuSplit(1);
                                cardOrderService.saveRow(order);
                                saveChargeData(order.getComId(),order.getMonthCardOrderId(),OrderAction.Baofu.BaofuBalanceIncrease,new Date(),
                                        actionEntity,"宝付分账月卡");

                                //添加宝付流水
                                addBaofuAccountDetails(accountDetails);
                                //添加商户流程
                                addMerchantBill(bills);
                            }

                        }
                    }
                    //严重数据
                }catch (Exception e){
                    log.error("订单："+order.getOutTradeNo()+" 分账失败,原因："+e.getMessage());
                }

            }
        }

        List<Order> fireOrders = orderService.getListBySqlName("get_baofu_split_fire_order_list",null);

        if(fireOrders!=null&&fireOrders.size()>0){
            log.info("执行消防服务订单分账");
            for(Order order:fireOrders){
                //查询分账数据
                try{
                    ValuesActionEntity actionEntity = null;
                    List<ValuesAcctInfoEntity> acctInfo =  new ArrayList<>();
                    ValuesAcctInfoEntity acctInfoEntity =  null;
                    List<BaofuCommissionItemVO> commissionItemVOS = orderService.getViewModelList("get_baofu_commission_list_byFire",BaofuCommissionItemVO.class,new Object[]{order.getChargeOrderId()});
                    if(commissionItemVOS!=null&&commissionItemVOS.size()>0){
                        List<BaofuAccountDetails> accountDetails = new ArrayList<>();
                        List<BaofuCommissionItemVO> vlist = commissionItemVOS.stream().filter(e->StrUtil.isBlank(e.getBaofuUserId())).collect(Collectors.toList());
                        if(vlist != null && vlist.size()>0){
                            vlist.forEach(e->{
                                log.info("用户："+e.getName()+" 未开户，所以此订单暂不支持分账，订单id:"+e.getChargeOrderId());
                            });
                        }else {
                            Integer dealAmount = 0;
                            //分账操作
                            actionEntity = new ValuesActionEntity();
                            String transSerialNo =OrderUtil.getTxOrderNo();

                            //账户流水
                            List<MerchantBill> bills = new ArrayList<>();
                            for(BaofuCommissionItemVO vo:commissionItemVOS){
                                acctInfoEntity = new ValuesAcctInfoEntity();
                                acctInfoEntity.setContractNo(vo.getContractNo());
                                acctInfoEntity.setTransAmount(new BigDecimal(vo.getCommission()).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                                acctInfoEntity.setRemark("订单："+order.getOutTradeNo()+"进行比分账");
                                dealAmount = dealAmount + vo.getCommission();
                                acctInfo.add(acctInfoEntity);
                                //写人账户明细数据
                                BaofuAccountDetails details = new BaofuAccountDetails();
                                details.setCommissionId(vo.getChargeOrderCommissionId());
                                details.setContractNo(vo.getContractNo());
                                details.setCommission(vo.getCommission());
                                details.setCommissionRate(vo.getCommissionRate());
                                details.setChargeOrderId(order.getChargeOrderId());
                                details.setTransSerialNo(transSerialNo);
                                details.setOutTradeNo(order.getOutTradeNo());
                                details.setOrderAmount(order.getOrderAmount());
                                details.setAccountType(FinancialEnum.IncomeOrExpend.Income.name());
                                details.setType(BaofuEnum.OrderType.fire.name());
                                details.setCreateTime(new Date());
                                //details.setBaofuAccountDetailsId(UUID.randomUUID().toString().replaceAll("-",""));
                                accountDetails.add(details);

                                bills.add(getMerchantBill(order.getComId(), vo.getPlatformMerchantId(), vo.getCommission(),order.getOutTradeNo()));
                            }
                            actionEntity.setAcctInfo(acctInfo);
                            actionEntity.setTransOrderNo("TSN"+ FormatUtil.CreateAeskey(20));
                            actionEntity.setTransSerialNo(transSerialNo);
                            actionEntity.setOrderNo(order.getOutTradeNo());
                            actionEntity.setDealAmount(new BigDecimal(dealAmount).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                            ContentBodyEntity<RsultBodyEntity> contentBody = baoFuAccountService.BCT3_5001_001_01(actionEntity);
                            if (contentBody.getBody().getState() == 1){
                                //修改订单状态
                                order.setIsBaofuFireSplit(1);
                                orderService.saveRow(order);
                                saveChargeData(order.getComId(),order.getChargeOrderId(),OrderAction.Baofu.BaofuBalanceIncrease,new Date(),
                                        actionEntity,"宝付分账(消防服务费)");
                                //添加宝付流水
                                addBaofuAccountDetails(accountDetails);
                                //添加商户流程
                                addMerchantBill(bills);
                            }

                        }
                    }


                    //严重数据
                }catch (Exception e){
                    log.error("订单："+order.getOutTradeNo()+" 分账失败（消防服务费）,原因："+e.getMessage());
                }
            }
        }
    }

    /**
     * 宝付提现定时任务，每天晚上12点执行
     */
    @Async
    @Scheduled(cron = "${baofu.account.cashoutCron}")
    @Profile({"dev"})
    public void cashoutBaofu() {
        log.info("执行提现定时任务");
        baofuManager.schEduledCashout();

    }
    /**
     * 保存记录订单操作日志
     * @param orderId 订单ID
     * @param action 操作类型
     * @param time 时间
     * @param data 其他数据
     * @param remark 描述
     */
    public void saveChargeData(String comId, String orderId, OrderAction.Baofu action, Date time, Object data, String remark){
        DataLog dataLog = new DataLog();
        dataLog.setComId(comId);
        dataLog.setChargeOrderId(orderId);
        dataLog.setAction(action.name());
        dataLog.setActionZh(action.getValue());
        dataLog.setCreateTime(time);
        dataLog.setJsonData(cn.hutool.json.JSONUtil.toJsonStr(data));
        dataLog.setRemark(remark);
        dataLogService.saveRow(dataLog);
    }

    public  void addBaofuAccountDetails(List<BaofuAccountDetails> baofuAccountDetails) {
        if(baofuAccountDetails!=null && baofuAccountDetails.size()>0){
            for (BaofuAccountDetails item : baofuAccountDetails) {
                accountDetailsService.saveRow(item);
            }
        }
    }

    public MerchantBill getMerchantBill(String comId, String platformMerchantId,int amount,String outTradeNo){
        MerchantBill merchantBill = new MerchantBill();
        merchantBill.setComId(comId);
        merchantBill.setPlatformMerchantId(platformMerchantId);
        merchantBill.setOutTradeNo(outTradeNo);
        merchantBill.setAmount(amount);
        merchantBill.setCreateTime(new Date());
        merchantBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());
        merchantBill.setStatus(FinancialEnum.BillStatus.Effective.name());
        merchantBill.setEvent(FinancialEnum.MerchantBillEvent.SplitAccounts.name());
        merchantBill.setNo(StrUtil.builder(DateUtil.date().toString(DatePattern.PURE_DATETIME_MS_PATTERN), RandomUtil.randomNumbers(4)).toString());
        return merchantBill;
    }

    public  void addMerchantBill(List<MerchantBill> bills) {
        if(bills!=null && bills.size()>0){
            for (MerchantBill item : bills) {
                merchantBillService.saveRow(item);
                //添加平台流水
                PlatformBill platformBill = new PlatformBill();
                platformBill.setOutTradeNo(item.getOutTradeNo());
                platformBill.setAmount(item.getAmount());
                platformBill.setCreateTime(new Date());
                platformBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());
                platformBill.setStatus(FinancialEnum.BillStatus.Effective.name());
                platformBill.setEvent(FinancialEnum.MerchantBillEvent.SplitAccounts.name());
                platformBill.setNo(StrUtil.builder(DateUtil.date().toString(DatePattern.PURE_DATETIME_MS_PATTERN), RandomUtil.randomNumbers(4)).toString());
                platformBillService.saveRow(platformBill);
            }
        }
    }

}
